package com.hl.order.controller;

import java.math.BigDecimal;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.hl.order.domain.Orders;
import com.hl.order.service.IOrdersService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

import java.util.Map;
import java.util.HashMap;

/**
 * 订单查询Controller
 * 
 * @author ruoyi
 * @date 2025-08-07
 */
@RestController
@RequestMapping("/orders")
public class OrdersController extends BaseController
{
    @Autowired
    private IOrdersService ordersService;

    /**
     * 查询订单查询列表
     */
    // @RequiresPermissions("order:orders:list")
    @GetMapping("/list")
    public TableDataInfo list(Orders orders)
    {
        startPage();
        List<Orders> list = ordersService.selectOrdersList(orders);
        return getDataTable(list);
    }

    /**
     * 导出订单查询列表
     */
//    @RequiresPermissions("order:orders:export")
    @Log(title = "订单查询", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Orders orders)
    {
        List<Orders> list = ordersService.selectOrdersList(orders);
        ExcelUtil<Orders> util = new ExcelUtil<Orders>(Orders.class);
        util.exportExcel(response, list, "订单查询数据");
    }

    /**
     * 获取订单查询详细信息
     */
//    @RequiresPermissions("order:orders:query")
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") Long orderId)
    {
        return success(ordersService.selectOrdersByOrderId(orderId));
    }

    /**
     * 新增订单查询
     */
//    @RequiresPermissions("order:orders:add")
    @Log(title = "订单查询", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Orders orders)
    {
        return toAjax(ordersService.insertOrders(orders));
    }

    /**
     * 修改订单查询
     */
//    @RequiresPermissions("order:orders:edit")
    @Log(title = "订单查询", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Orders orders)
    {
        return toAjax(ordersService.updateOrders(orders));
    }

    /**
     * 删除订单查询
     */
//    @RequiresPermissions("order:orders:remove")
    @Log(title = "订单查询", businessType = BusinessType.DELETE)
	@DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable Long[] orderIds)
    {
        return toAjax(ordersService.deleteOrdersByOrderIds(orderIds));
    }

    /**
     * 根据店铺ID查询今日支付的订单数量
     */
//    @RequiresPermissions("order:orders:query")
//    @GetMapping("/todayPaidCount/{shopId}")
    public AjaxResult getTodayPaidOrderCount(@PathVariable("shopId") Long shopId)
    {
        System.out.println(ordersService.countTodayPaidOrdersByShopId(shopId));
       return success(ordersService.countTodayPaidOrdersByShopId(shopId));

    }

    /**
     * 根据店铺ID查询今日商家实际收入
     */
//    @RequiresPermissions("order:orders:query")
    @GetMapping("/todayBusinessIncome/{shopId}")
    public AjaxResult getTodayBusinessIncome(@PathVariable("shopId") Long shopId)
    {
        try {
            BigDecimal income = ordersService.getTodayBusinessIncomeByShopId(shopId);
            return AjaxResult.success("查询成功", income);
        } catch (Exception e) {
            logger.error("查询今日商家收入失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据店铺ID查询未到账的订单总数
     */
//    @RequiresPermissions("order:orders:query")
    @GetMapping("/unpaidToMerchantCount/{shopId}")
    public AjaxResult getUnpaidToMerchantOrderCount(@PathVariable("shopId") Long shopId)
    {
        try {
            int count = ordersService.countUnpaidToMerchantOrdersByShopId(shopId);
            return AjaxResult.success("查询成功", count);
        } catch (Exception e) {
            logger.error("查询未到账订单数量失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

//根据用户ID查询所有订单
    @GetMapping("/getAllOrdersByUserId/{userId}")
    public List<Orders> getAllOrdersByUserId(@PathVariable("userId") Long userId)
    {
       return   ordersService.getAllOrdersByUserId(userId);
    }




    /**
     * 根据店铺ID查询已售后的订单总数
     */
//    @RequiresPermissions("order:orders:query")
    @GetMapping("/afterSalesCount/{shopId}")
    public AjaxResult getAfterSalesOrderCount(@PathVariable("shopId") Long shopId)
    {
        try {
            int count = ordersService.countAfterSalesOrdersByShopId(shopId);
            return AjaxResult.success("查询成功", count);
        } catch (Exception e) {
            logger.error("查询已售后订单数量失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据店铺ID查询待支付订单数量
     */
//    @RequiresPermissions("order:orders:query")
    @GetMapping("/pendingPaymentCount/{shopId}")
    public AjaxResult getPendingPaymentOrderCount(@PathVariable("shopId") Long shopId)
    {
        try {
            int count = ordersService.countPendingPaymentOrdersByShopId(shopId);
            return AjaxResult.success("查询成功", count);
        } catch (Exception e) {
            logger.error("查询待支付订单数量失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据店铺ID查询待配送订单数量
     */
//    @RequiresPermissions("order:orders:query")
    @GetMapping("/pendingDeliveryCount/{shopId}")
    public AjaxResult getPendingDeliveryOrderCount(@PathVariable("shopId") Long shopId)
    {
        try {
            int count = ordersService.countPendingDeliveryOrdersByShopId(shopId);
            return AjaxResult.success("查询成功", count);
        } catch (Exception e) {
            logger.error("查询待配送订单数量失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据店铺ID查询已完成订单数量
     */
//    @RequiresPermissions("order:orders:query")
    @GetMapping("/completedCount/{shopId}")
    public AjaxResult getCompletedOrderCount(@PathVariable("shopId") Long shopId)
    {
        try {
            int count = ordersService.countCompletedOrdersByShopId(shopId);
            return AjaxResult.success("查询成功", count);
        } catch (Exception e) {
            logger.error("查询已完成订单数量失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据店铺ID查询售后处理中订单数量
     */
//    @RequiresPermissions("order:orders:query")
    @GetMapping("/afterSalesProcessingCount/{shopId}")
    public AjaxResult getAfterSalesProcessingOrderCount(@PathVariable("shopId") Long shopId)
    {
        try {
            int count = ordersService.countAfterSalesProcessingOrdersByShopId(shopId);
            return AjaxResult.success("查询成功", count);
        } catch (Exception e) {
            logger.error("查询售后处理中订单数量失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    // ====== 指数统计相关接口 ======

    /**
     * 根据店铺ID查询今日订单总数（所有状态）
     */
//    @RequiresPermissions("order:orders:query")
    @GetMapping("/todayAllCount/{shopId}")
    public AjaxResult getTodayAllOrderCount(@PathVariable("shopId") Long shopId)
    {
        try {
            int count = ordersService.countTodayAllOrdersByShopId(shopId);
            return AjaxResult.success("查询成功", count);
        } catch (Exception e) {
            logger.error("查询今日订单总数失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据店铺ID查询待处理订单总数（待支付+待配送）
     */
//    @RequiresPermissions("order:orders:query")
    @GetMapping("/pendingCount/{shopId}")
    public AjaxResult getPendingOrderCount(@PathVariable("shopId") Long shopId)
    {
        try {
            int count = ordersService.countPendingOrdersByShopId(shopId);
            return AjaxResult.success("查询成功", count);
        } catch (Exception e) {
            logger.error("查询待处理订单总数失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据店铺ID查询本月订单总数
     */
//    @RequiresPermissions("order:orders:query")
    @GetMapping("/monthCount/{shopId}")
    public AjaxResult getMonthOrderCount(@PathVariable("shopId") Long shopId)
    {
        try {
            int count = ordersService.countMonthOrdersByShopId(shopId);
            return AjaxResult.success("查询成功", count);
        } catch (Exception e) {
            logger.error("查询本月订单总数失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据店铺ID查询订单总数（用于计算完成率）
     */
//    @RequiresPermissions("order:orders:query")
    @GetMapping("/allCount/{shopId}")
    public AjaxResult getAllOrderCount(@PathVariable("shopId") Long shopId)
    {
        try {
            int count = ordersService.countAllOrdersByShopId(shopId);
            return AjaxResult.success("查询成功", count);
        } catch (Exception e) {
            logger.error("查询订单总数失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    // ====== 图表数据相关接口 ======

    /**
     * 根据店铺ID和日期范围查询每日订单数量
     */
//    @RequiresPermissions("order:orders:query")
    @GetMapping("/dailyOrdersChart/{shopId}")
    public AjaxResult getDailyOrdersChart(
            @PathVariable("shopId") Long shopId,
            @RequestParam("startDate") String startDate,
            @RequestParam("endDate") String endDate)
    {
        try {
            List<Map<String, Object>> chartData = ordersService.getDailyOrdersChart(shopId, startDate, endDate);
            
            Map<String, Object> result = new HashMap<>();
            result.put("title", "每日订单数量");
            result.put("unit", "单");
            result.put("data", chartData);

            return AjaxResult.success("查询成功", result);
        } catch (Exception e) {
            logger.error("查询每日订单数量失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }

    // ====== 订单统计相关接口 ======

    /**
     * 根据店铺ID查询订单统计数据（本月、本周、上月、上周）
     */
//    @RequiresPermissions("order:orders:query")
    @GetMapping("/orderStats/{shopId}")
    public AjaxResult getOrderStats(@PathVariable("shopId") Long shopId)
    {
        try {
            // 并行获取四个时间段的统计数据
            Map<String, Object> monthStats = ordersService.getMonthOrderStats(shopId);
            Map<String, Object> weekStats = ordersService.getWeekOrderStats(shopId);
            Map<String, Object> previousMonthStats = ordersService.getPreviousMonthOrderStats(shopId);
            Map<String, Object> previousWeekStats = ordersService.getPreviousWeekOrderStats(shopId);

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            
            // 当前数据
            result.put("monthTotal", monthStats.get("orderCount"));
            result.put("weekTotal", weekStats.get("orderCount"));
            result.put("monthSales", monthStats.get("salesAmount"));
            result.put("weekSales", weekStats.get("salesAmount"));
            
            // 上期数据（用于计算同比）
            result.put("previousMonthTotal", previousMonthStats.get("orderCount"));
            result.put("previousWeekTotal", previousWeekStats.get("orderCount"));
            result.put("previousMonthSales", previousMonthStats.get("salesAmount"));
            result.put("previousWeekSales", previousWeekStats.get("salesAmount"));

            return AjaxResult.success("查询成功", result);
        } catch (Exception e) {
            logger.error("查询订单统计数据失败", e);
            return AjaxResult.error("查询失败：" + e.getMessage());
        }
    }


}
